<?php

namespace app\admin\controller;


use app\common\controller\AdminController;
use app\admin\model\SystemAdmin;

/**
 * @package app\admin\controller
 */
class Login extends AdminController
{

    /**
     * 用户登录
     * @return string
     * @throws \Exception
     */
    public function login()
    {
        $post = $this->request->post();
        $rule = [
            'username|用户名'      => 'require',
            'password|密码'       => 'require',
        ];
        $this->validate($post, $rule);
        $admin = SystemAdmin::where(['username' => $post['username']])->find();
        if (empty($admin)) {
            $this->error('用户不存在');
        }
        if (password($post['password']) != $admin->password) {
            $this->error('密码输入有误');
        }
        if ($admin->status == 0) {
            $this->error('账号已被禁用');
        }
        $ym = date('Ym');
        $access_token = $admin->access_token;
        if (strpos($access_token, $ym) !== 0) {
            $access_token = $ym.md5(time().uniqid().rand(1,9999));
        }
        $admin->login_num += 1;
        $admin->access_token = $access_token;
        //$admin->token_expire_time = now_time() + 3600*24*7;
        $admin->save();
        $admin = $admin->toArray();
        $this->success(['username'=>$admin['username'], 'access_token'=> $access_token]);
    }

    /**
     * 用户退出
     * @return mixed
     */
    public function out()
    {
        $this->success();
    }
}
